package com.xuesinuo.pignoo.autodatabase;

import java.lang.reflect.Modifier;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import javax.sql.DataSource;

import com.xuesinuo.pignoo.autodatabase.entity.DatabaseCheckResult;
import com.xuesinuo.pignoo.autodatabase.exception.ScanException;
import com.xuesinuo.pignoo.autodatabase.impl.DatabaseChecker4MySql;
import com.xuesinuo.pignoo.core.PignooConfig;
import com.xuesinuo.pignoo.core.annotation.Table;
import com.xuesinuo.pignoo.core.config.DatabaseEngine;
import com.xuesinuo.pignoo.core.entity.EntityMapper;
import com.xuesinuo.pignoo.core.exception.DataSourceException;

import io.github.classgraph.ClassGraph;
import io.github.classgraph.ClassInfo;
import io.github.classgraph.ClassInfoList;
import io.github.classgraph.ScanResult;
import lombok.extern.slf4j.Slf4j;

/**
 * 实体扫描器
 * <p>
 * Entity scanner
 * 
 * @author xuesinuo
 * @since 0.3.0
 * @version 0.3.0
 */
@Slf4j
public class EntityScaner {
    private final DataSource dataSource;

    private final PignooConfig pignooConfig;

    private final EntityScanConfig entityScanConfig;

    private final DatabaseChecker databaseChecker;

    public EntityScaner(DataSource dataSource, PignooConfig pignooConfig, EntityScanConfig entityScanConfig) {
        this.dataSource = dataSource;
        this.pignooConfig = pignooConfig.copy();
        this.entityScanConfig = entityScanConfig.copy();
        if (pignooConfig.getEngine() == null) {
            try (Connection conn = dataSource.getConnection()) {
                pignooConfig.setEngine(DatabaseEngine.getDatabaseEngineByConnection(conn));
                if (!conn.getAutoCommit()) {
                    conn.commit();
                }
            } catch (SQLException e) {
                throw new DataSourceException("Search database engine error", e);
            }
        }
        switch (pignooConfig.getEngine()) {
        case DatabaseEngine.MySQL:
            this.databaseChecker = new DatabaseChecker4MySql(dataSource, entityScanConfig.getTypeMapper(), entityScanConfig.getStrictColumnType());
            break;
        default:
            throw new DataSourceException("Unknow database engine");
        }
    }

    /**
     * 扫描指定包下的所有实体类
     * <p>
     * Scan all entity classes under the specified package
     * 
     * @return 实体Mapper集合
     *         <p>
     *         EntityMapper collection
     */
    private Set<EntityMapper<?>> scanPackage() {
        entityScanConfig.setPackages(entityScanConfig.getPackages() == null ? new String[0] : entityScanConfig.getPackages());
        entityScanConfig.setClassesForScanPackage(entityScanConfig.getClassesForScanPackage() == null ? new Class<?>[0] : entityScanConfig.getClassesForScanPackage());
        HashSet<String> packages = new HashSet<>(entityScanConfig.getPackages().length + entityScanConfig.getClassesForScanPackage().length);
        for (String packageStr : entityScanConfig.getPackages()) {
            if (packageStr != null && !packageStr.isBlank()) {
                packages.add(packageStr);
            }
        }
        for (Class<?> classForScanPackage : entityScanConfig.getClassesForScanPackage()) {
            if (classForScanPackage != null) {
                packages.add(classForScanPackage.getPackage().getName());
            }
        }
        if (packages.isEmpty()) {
            throw new DataSourceException("[Pignoo-Scan Error] Packages empty");
        }
        String[] packageArray = packages.toArray(new String[packages.size()]);
        ClassGraph classGraph = new ClassGraph();
        classGraph.enableAllInfo();
        if (entityScanConfig.getScanChildPackages()) {
            classGraph.acceptPackages(packageArray);
        } else {
            classGraph.acceptPackagesNonRecursive(packageArray);
        }
        Set<EntityMapper<?>> entityMappers = new HashSet<>();
        if (entityScanConfig.getAnnotationClassOnly()) {
            classGraph.enableAnnotationInfo();
        }
        try (ScanResult scanResult = classGraph.scan()) {
            ClassInfoList classInfo4GraphList = null;
            if (entityScanConfig.getAnnotationClassOnly()) {
                classInfo4GraphList = scanResult.getClassesWithAnnotation(Table.class);
            } else {
                classInfo4GraphList = scanResult.getAllClasses();
            }
            classInfo4GraphList.stream()
                    .filter(classInfo -> isPublicClass(classInfo) || isStaticInnerClass(classInfo))// 只识别public静态内部类和public普通类
                    .forEach(classInfo4Graph -> {
                        Class<?> entityClass = classInfo4Graph.loadClass();
                        EntityMapper<?> mapper = null;
                        mapper = EntityMapper.build(entityClass, this.pignooConfig);
                        entityMappers.add(mapper);
                    });
        }
        return entityMappers;
    }

    private static boolean isPublicClass(ClassInfo classInfo) {
        Class<?> c;
        try {
            c = Class.forName(classInfo.getName());
        } catch (ClassNotFoundException e) {
            throw new ScanException("Can not read class " + classInfo.getName(), e);
        }
        if (c.getEnclosingClass() != null) {
            return false;
        }
        if (!Modifier.isPublic(c.getModifiers())) {
            return false;
        }
        return true;
    }

    private static boolean isStaticInnerClass(ClassInfo classInfo) {
        Class<?> c;
        try {
            c = Class.forName(classInfo.getName());
        } catch (ClassNotFoundException e) {
            throw new ScanException("Can not read class " + classInfo.getName(), e);
        }
        if (c.getEnclosingClass() == null) {
            return false;
        }
        if (!Modifier.isPublic(c.getModifiers())) {
            return false;
        }
        if (!Modifier.isStatic(c.getModifiers())) {
            return false;
        }
        return true;
    }

    /**
     * 扫描并构建
     * <p>
     * Scan and build
     */
    public void scan() {
        DatabaseCheckResult allResult = new DatabaseCheckResult();
        StringBuilder scanClassMsg = new StringBuilder();
        var packageMappers = scanPackage();
        for (EntityMapper<?> mapper : packageMappers) {
            DatabaseCheckResult itemResult = databaseChecker.check(mapper);
            allResult.getAdvise2AddTable().addAll(itemResult.getAdvise2AddTable());
            allResult.getAdvise2AddColumn().addAll(itemResult.getAdvise2AddColumn());
            allResult.getAdvise2UpdateColumn().addAll(itemResult.getAdvise2UpdateColumn());
            allResult.getAdvise2RemoveColumn().addAll(itemResult.getAdvise2RemoveColumn());
            allResult.getOtherMessage().addAll(itemResult.getOtherMessage());
            scanClassMsg.append(mapper.getType().getName()).append("\n");
        }
        if (!packageMappers.isEmpty()) {
            log.info("[Pignoo-Scan] Classes found:\n{}", scanClassMsg.toString() + "total " + packageMappers.size() + " entity(s).");
        } else {
            log.warn("[Pignoo-Scan] No class found");
        }
        String warningTitle = """

                ================================
                = Pingnoo-Autodatabase Warning =
                ================================
                """;
        List<String> adviseList = new ArrayList<>();
        StringBuilder warning = new StringBuilder(warningTitle);
        allResult.getOtherMessage().stream().forEach(msg -> warning.append(msg).append("\n"));
        if (this.entityScanConfig.getBuildMode() == EntityScanConfig.BuildMode.CAREFULLY) {
            allResult.getAdvise2RemoveColumn().stream().forEach(msg -> warning.append(msg).append(";\n"));
            allResult.getAdvise2UpdateColumn().stream().forEach(msg -> warning.append(msg).append(";\n"));
            allResult.getAdvise2AddColumn().stream().forEach(msg -> warning.append(msg).append(";\n"));
            allResult.getAdvise2AddTable().stream().forEach(msg -> warning.append(msg).append(";\n"));
        } else if (this.entityScanConfig.getBuildMode() == EntityScanConfig.BuildMode.SAFELY) {
            allResult.getAdvise2RemoveColumn().stream().forEach(msg -> warning.append(msg).append(";\n"));
            allResult.getAdvise2UpdateColumn().stream().forEach(msg -> warning.append(msg).append(";\n"));
            adviseList.addAll(allResult.getAdvise2AddColumn());
            adviseList.addAll(allResult.getAdvise2AddTable());
        } else if (this.entityScanConfig.getBuildMode() == EntityScanConfig.BuildMode.USABILITY) {
            allResult.getAdvise2RemoveColumn().stream().forEach(msg -> warning.append(msg).append(";\n"));
            adviseList.addAll(allResult.getAdvise2UpdateColumn());
            adviseList.addAll(allResult.getAdvise2AddColumn());
            adviseList.addAll(allResult.getAdvise2AddTable());
        } else if (this.entityScanConfig.getBuildMode() == EntityScanConfig.BuildMode.RADICALLY) {
            adviseList.addAll(allResult.getAdvise2RemoveColumn());
            adviseList.addAll(allResult.getAdvise2UpdateColumn());
            adviseList.addAll(allResult.getAdvise2AddColumn());
            adviseList.addAll(allResult.getAdvise2AddTable());
        }
        String warn = warning.toString();
        if (this.entityScanConfig.getBreakRunning() && !warn.equals(warningTitle)) {
            if (!adviseList.isEmpty()) {
                log.error("""

                        ===============================
                        = Pingnoo-Autodatabase Advise =
                        ===============================
                        """ + adviseList.stream().map(sql -> sql + ";\n").collect(Collectors.joining()));
            }
            log.error(warn);
            throw new ScanException("[Pignoo-Scan] Database check failed");
        }
        if (!adviseList.isEmpty()) {
            log.warn("""

                    ===============================
                    = Pingnoo-Autodatabase Advise =
                    ===============================
                    """ + adviseList.stream().map(sql -> sql + ";\n").collect(Collectors.joining()));
        }
        if (!warn.equals(warningTitle)) {
            log.warn(warn);
        }
        if (!adviseList.isEmpty()) {
            Connection conn = null;
            Boolean autoCommit = null;
            String workSql = null;
            try {
                conn = dataSource.getConnection();
                autoCommit = conn.getAutoCommit();
                conn.setAutoCommit(false);
                for (String workingItem : adviseList) {
                    workSql = workingItem;
                    conn.createStatement().execute(workSql);
                }
                conn.commit();
                log.warn("[Pignoo-Scan] Advise SQLs executed successfully!");
            } catch (SQLException e) {
                throw new ScanException("[Pignoo-Scan] Auto-Database run failed: " + workSql, e);
            } finally {
                Exception e = null;
                if (conn != null && autoCommit != null) {
                    try {
                        conn.setAutoCommit(autoCommit);
                    } catch (SQLException ex) {
                        e = ex;
                        log.error("[Pignoo-Scan] Set auto commit failed At running auto-database");
                    }
                }
                if (conn != null) {
                    try {
                        conn.close();
                    } catch (SQLException ex) {
                        e = ex;
                        log.error("[Pignoo-Scan] Close connection failed At running auto-database");
                    }
                }
                if (e != null) {
                    throw new ScanException("[Pignoo-Scan] Connetction error", e);
                }
            }
        }
        if (warning.toString().equals(warningTitle) && adviseList.isEmpty()) {
            log.info("[Pignoo-Scan Result] Nothing to do");
        } else {
            log.info("[Pignoo-Scan Result] Done");
        }
    }
}
